import requests,random,json
import demjson
from pyquery import PyQuery as pq
from com.lechebang.Setting import *


def parse(data):
    result={}
    brands=[]
    factories=[]
    carserials=[]
    for key, v in data.items():
        # print("====>" + key)
        for item in v:
            brand={}
            brand['id']=item['id']
            brand['name']=item['name']
            brand['type']=item['type']
            brand['index']=key
            brand['url']= item['url']
            brand['cur']= item['cur']
            brand['num']= item['num']
            brands.append(brand)

            # factory data
            if item.__contains__('child'):
                factory={}
                data_factory=item['child']
                for item2 in data_factory:
                    factory['name']=item2['name']
                    factory['type'] = item2['type']
                    factory['brand']=brand['name']
                    factory['url'] = item2['url']
                    factory['cur'] = item2['cur']
                    factory['num'] = item2['num']
                    factories.append(factory)

                    #car serial
                    if item2.__contains__('child'):
                        cs={}
                        data_cs=item2['child']
                        for item3 in data_cs:
                            cs['name'] = item3['name']
                            cs['type'] = item3['type']
                            cs['factory'] = factory['name']
                            cs['url'] = item3['url']
                            cs['cur'] = item3['cur']
                            cs['num'] = item3['num']
                            carserials.append(cs)

    # print(brands)
    result['brands']=brands
    result['factory']=factories
    result['carserials']=carserials
    print(result)
    return result


def get_brand_factory_cs(province):
    # url=URL_BRAND_FACTORY % ('guangdong')
    url = 'https://apicar.bitauto.com/CarInfo/getlefttreejson.ashx?tagtype=jingxiaoshang&pagetype=masterbrand&objid=9&citycode=guangdong/&cityid=5&showtype=1&carids=m9%7C#'
    print(url)
    headersData=get_headers()
    if(headersData==None):
        print("====>request init error!!!!!")
        return

    result=requests.get(url,headers=headersData)
    if result.status_code==200:
        tmp=result.text
        # print(content)
        print(tmp.find("{"))
        content=tmp[tmp.find("{"):-1]
        brands=demjson.decode(content,"utf-8")
        brandData=brands['brand']
        # print(brandData)
        result=parse(brandData)
        return result
    else:
        return None


def get_headers():
    ua = random.choice(USER_AGENT_LIST)
    if ua:
        headers={}
        headers['User-Agent']=ua
        return headers
    return None

if __name__ == '__main__':
    get_brand_factory_cs('guangdong')